package com.my.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.my.demo.pojo.Result;
import com.my.demo.pojo.User;
import com.my.demo.service.UserService;

import com.my.demo.utils.SaltUtils;
import com.my.demo.shiro.token.SmsToken;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
//进行忘记密码修改密码的Controller
public class ChangePasswordController {
  @Autowired
  UserService userService;

  //验证输入的验证码正确性
  @PostMapping("/changePassword")
  public Result changePassword(@RequestBody Map<String, String> models) {
    //构造返回结果
    Result result = new Result();
    result.setSuccess(false);
    result.setDetail(null);

    Subject subject= SecurityUtils.getSubject();

    String userName = models.get("userName");
    String verifyCode = models.get("verifyCode");
    String token=models.get("detail");
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("user_name", userName);
    User existUser = userService.getOne(wrapper);
    // 判断查询结果(result)是否为null
    if (existUser == null) {
      // 是：抛出UserNotFoundException
      result.setMsg("用户不存在");
    } else {
      try {
        subject.login(new SmsToken(userName,verifyCode,token));
        result.setMsg("验证成功");
        result.setSuccess(true);
        subject.logout();
      }catch (Exception e){
        result.setMsg("验证码错误");
      }
    }
    return result;
  }

  //验证正确进行修改密码
  @PostMapping("/updatePassword")
  public Result updatePassword(@RequestBody Map<String, String> map) {
    Result result = new Result();
    result.setSuccess(false);
    result.setDetail(null);

    String userName = map.get("userName");
    String password = map.get("password");

    //1.生成随机盐
    String salt = SaltUtils.getSalt(6);
    //2.明文密码进行md5 + salt + hash散列
    Md5Hash md5Hash = new Md5Hash(password,salt,1024);
    String new_password=md5Hash.toHex();

    UpdateWrapper<User> wrapper = new UpdateWrapper<>();
    wrapper.eq("user_name", userName).set("password", new_password);
    wrapper.eq("user_name", userName).set("salt", salt);
    boolean bool = userService.update(null, wrapper);

    if (bool) {
      result.setMsg("修改密码成功");
      result.setSuccess(false);
    } else {
      result.setMsg("修改密码失败");
    }
    return result;
  }
}
